import React, { useState, useCallback, useEffect } from "react";
import { Input, Typography, Button, notification } from "antd";
import { EditOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import {
  saveSpecificUserConfig,
  getSpecificUserConfig,
  CONFIG_TYPES,
} from "@/utils/helpers";

interface ProjectHeaderProps {
  userId: string;
  onShowTour: () => void;
}

export interface ProjectHeaderRef {
  loadProjectName: () => Promise<void>;
  projectName: string;
}

const ProjectHeader = React.forwardRef<ProjectHeaderRef, ProjectHeaderProps>(
  ({ userId, onShowTour }, ref) => {
    const [projectName, setProjectName] = useState<string>("我的项目-未命名");
    const [isEditingProjectName, setIsEditingProjectName] =
      useState<boolean>(false);
    const [tempProjectName, setTempProjectName] =
      useState<string>("我的项目-未命名");

    // 保存项目名称配置
    const saveProjectNameConfig = useCallback(
      async (name: string) => {
        try {
          const success = await saveSpecificUserConfig(
            userId,
            CONFIG_TYPES.PROJECT_NAME,
            { name },
          );
          if (success) {
            notification.success({
              message: "项目名称已保存",
              placement: "topRight",
              duration: 2,
            });
          } else {
            notification.error({
              message: "保存失败",
              description: "项目名称保存失败，请重试",
              placement: "topRight",
              duration: 3,
            });
          }
        } catch (error) {
          notification.error({
            message: "保存失败",
            description: "项目名称保存失败，请重试",
            placement: "topRight",
            duration: 3,
          });
        }
      },
      [userId],
    );

    // 加载保存的项目名称
    const loadProjectName = useCallback(async () => {
      try {
        const projectNameConfig = await getSpecificUserConfig(
          userId,
          CONFIG_TYPES.PROJECT_NAME,
        );
        if (projectNameConfig && projectNameConfig.name) {
          setProjectName(projectNameConfig.name);
          setTempProjectName(projectNameConfig.name);
        }
      } catch (error) {
        console.error("加载项目名称失败:", error);
      }
    }, [userId]);

    // 处理项目名称编辑
    const handleProjectNameEdit = () => {
      setIsEditingProjectName(true);
      setTempProjectName(projectName);
    };

    const handleProjectNameSave = () => {
      const trimmedName = tempProjectName.trim();
      if (trimmedName && trimmedName !== projectName) {
        setProjectName(trimmedName);
        saveProjectNameConfig(trimmedName);
      }
      setIsEditingProjectName(false);
    };

    const handleProjectNameCancel = () => {
      setTempProjectName(projectName);
      setIsEditingProjectName(false);
    };

    const handleProjectNameKeyPress = (e: React.KeyboardEvent) => {
      if (e.key === "Enter") {
        handleProjectNameSave();
      } else if (e.key === "Escape") {
        handleProjectNameCancel();
      }
    };

    // 暴露方法给父组件
    React.useImperativeHandle(ref, () => ({
      loadProjectName,
      projectName,
    }));

    // 组件挂载时加载项目名称
    useEffect(() => {
      loadProjectName();
    }, [loadProjectName]);

    // 渲染可编辑的项目名称
    const renderEditableProjectName = () => {
      if (isEditingProjectName) {
        return (
          <Input
            value={tempProjectName}
            onChange={(e) => setTempProjectName(e.target.value)}
            onBlur={handleProjectNameSave}
            onPressEnter={handleProjectNameSave}
            onKeyDown={handleProjectNameKeyPress}
            autoFocus
            style={{
              fontSize: "20px",
              fontWeight: 600,
              border: "1px solid #1890ff",
              borderRadius: "4px",
              padding: "4px 8px",
              width: "auto",
              minWidth: "120px",
              maxWidth: "300px",
            }}
            placeholder="请输入项目名称"
            maxLength={50}
          />
        );
      }

      return (
        <div
          onClick={handleProjectNameEdit}
          style={{
            display: "flex",
            alignItems: "center",
            cursor: "pointer",
            padding: "4px 8px",
            borderRadius: "4px",
            transition: "background-color 0.2s",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = "#f5f5f5";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = "transparent";
          }}
        >
          <Typography.Title
            level={2}
            style={{
              margin: 0,
              fontSize: "20px",
              fontWeight: 600,
            }}
          >
            {projectName}
          </Typography.Title>
          <EditOutlined
            style={{
              marginLeft: "8px",
              color: "#8c8c8c",
              fontSize: "14px",
            }}
          />
        </div>
      );
    };

    return (
      <div
        style={{
          height: "80px",
          borderBottom: "1px solid #d9d9d9",
          display: "flex",
          alignItems: "center",
          padding: "0 24px",
          flexShrink: 0,
        }}
      >
        {renderEditableProjectName()}

        <div
          style={{
            marginLeft: "auto",
            display: "flex",
            gap: "12px",
            alignItems: "center",
          }}
        >
          <Button
            icon={<QuestionCircleOutlined />}
            onClick={onShowTour}
            style={{ position: "static" }}
          >
            使用教程
          </Button>
        </div>
      </div>
    );
  },
);

ProjectHeader.displayName = "ProjectHeader";

export default ProjectHeader;
